<template>
  <view class="chat-page">
    <!-- 顶部导航栏 -->
    <view class="navbar" :style="{ height: (navBarHeight) + 'px', paddingTop: (statusBarHeight) + 'px' }">
      <view class="nav-left" @tap="goBack">
        <text class="icon-back">‹</text>
      </view>
      <text class="nav-title">在线客服</text>
      <view class="nav-right"></view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-content" 
      :style="{ paddingTop: (navBarHeight + 20) + 'px' }"
      scroll-y 
      :scroll-into-view="scrollIntoView"
      scroll-with-animation
    >
      <!-- 欢迎消息 -->
      <view class="message-item bot-message" id="msg-welcome">
        <view class="avatar bot-avatar">
          <image src="/static/logo.png" mode="aspectFill" />
        </view>
        <view class="message-wrapper">
          <view class="message-bubble bot-bubble">
            <text class="message-text">您好！我是黄山智能客服，很高兴为您服务。\n\n您可以询问：\n• 黄山景点介绍\n• 门票预订\n• 交通指南\n• 住宿推荐\n• 美食攻略\n• 登山注意事项\n• 天气查询</text>
          </view>
          <text class="message-time">{{ formatTime(new Date()) }}</text>
        </view>
      </view>

      <!-- 聊天消息列表 -->
      <view 
        v-for="(msg, index) in messages" 
        :key="index" 
        class="message-item"
        :class="msg.type === 'user' ? 'user-message' : 'bot-message'"
        :id="'msg-' + index"
      >
        <!-- 机器人消息 -->
        <template v-if="msg.type === 'bot'">
          <view class="avatar bot-avatar">
            <image src="/static/logo.png" mode="aspectFill" />
          </view>
          <view class="message-wrapper">
            <view class="message-bubble bot-bubble">
              <text class="message-text">{{ msg.content }}</text>
            </view>
            <text class="message-time">{{ msg.time }}</text>
          </view>
        </template>

        <!-- 用户消息 -->
        <template v-else>
          <view class="message-wrapper">
            <view class="message-bubble user-bubble">
              <text class="message-text">{{ msg.content }}</text>
            </view>
            <text class="message-time">{{ msg.time }}</text>
          </view>
          <view class="avatar user-avatar">
            <text class="avatar-text">我</text>
          </view>
        </template>
      </view>

      <!-- 加载中提示 -->
      <view v-if="isLoading" class="message-item bot-message">
        <view class="avatar bot-avatar">
          <image src="/static/logo.png" mode="aspectFill" />
        </view>
        <view class="message-wrapper">
          <view class="message-bubble bot-bubble typing">
            <text class="dot"></text>
            <text class="dot"></text>
            <text class="dot"></text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 快捷问题浮动按钮 -->
    <view class="quick-float-btn" @tap="openQuickDialog">
      <text class="quick-icon">💬</text>
    </view>

    <!-- 快捷问题弹窗 -->
    <view class="quick-dialog-mask" v-if="showQuickDialog" @tap="closeQuickDialog">
      <view class="quick-dialog" @tap.stop>
        <view class="quick-header">
          <text class="quick-title">快捷问题</text>
          <text class="quick-close" @tap="closeQuickDialog">×</text>
        </view>
        <view class="quick-list">
          <view 
            v-for="(q, i) in quickQuestions" 
            :key="i" 
            class="quick-item"
            @tap="sendQuickQuestion(q)"
          >
            <text class="quick-icon-small">💬</text>
            <text class="quick-text">{{ q }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部输入栏 -->
    <view class="input-bar">
      <input 
        class="input-text" 
        v-model="inputText" 
        placeholder="请输入您的问题..."
        confirm-type="send"
        @confirm="sendMessage"
      />
      <view 
        class="send-btn" 
        :class="{ 'active': inputText.trim() }"
        @tap="sendMessage"
      >
        发送
      </view>
    </view>

    <!-- SOS紧急按钮 -->
    <emergency-sos bottom="200" right="24" />
  </view>
</template>

<script>
import request from '@/utils/request'
import EmergencySOS from '@/components/emergency-sos/emergency-sos.vue'

export default {
  components: { EmergencySOS },
  data() {
    return {
      statusBarHeight: 0,
      navBarHeight: 0,
      inputText: '',
      messages: [],
      isLoading: false,
      scrollIntoView: '',
      showQuickDialog: false,
      quickQuestions: [
        '黄山门票多少钱？',
        '迎客松怎么去？',
        '黄山有什么景点？',
        '山上有住宿吗？',
        '黄山天气怎么样？',
        '黄山有什么美食？',
        '登山需要准备什么？',
        '如何预订配爬员？'
      ]
    }
  },
  
  created() {
    const info = uni.getSystemInfoSync && uni.getSystemInfoSync()
    this.statusBarHeight = (info && info.statusBarHeight) ? info.statusBarHeight : 20
    // 导航栏总高度 = 状态栏高度 + 导航栏内容高度(44px)
    this.navBarHeight = this.statusBarHeight + 44
  },
  
  methods: {
    // 返回首页
    goBack() {
      uni.reLaunch({
        url: '/pages/index'
      })
    },
    
    // 发送消息
    async sendMessage() {
      const text = this.inputText.trim()
      if (!text) {
        return
      }
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: text,
        time: this.formatTime(new Date())
      })
      
      // 清空输入框
      this.inputText = ''
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      // 显示加载状态
      this.isLoading = true
      
      try {
        // 调用后端接口
        const response = await request({
          url: '/chat/query',
          method: 'POST',
          data: {
            question: text
          }
        })
        
        // 隐藏加载状态
        this.isLoading = false
        
        if (response.code === 200 && response.data) {
          // 添加机器人回复
          this.messages.push({
            type: 'bot',
            content: response.data.replyContent || '抱歉，我暂时无法理解您的问题。',
            time: this.formatTime(new Date()),
            matched: response.data.matched
          })
        } else {
          this.messages.push({
            type: 'bot',
            content: '抱歉，服务出现异常，请稍后再试。',
            time: this.formatTime(new Date()),
            matched: false
          })
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        this.isLoading = false
        this.messages.push({
          type: 'bot',
          content: '网络异常，请检查网络连接后重试。',
          time: this.formatTime(new Date()),
          matched: false
        })
      }
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    // 发送快捷问题
    sendQuickQuestion(question) {
      this.inputText = question
      this.showQuickDialog = false
      this.sendMessage()
    },
    
    // 打开快捷问题弹窗
    openQuickDialog() {
      this.showQuickDialog = true
    },
    
    // 关闭快捷问题弹窗
    closeQuickDialog() {
      this.showQuickDialog = false
    },
    
    // 滚动到底部
    scrollToBottom() {
      const index = this.messages.length - 1
      if (index >= 0) {
        this.scrollIntoView = 'msg-' + index
      }
    },
    
    // 格式化时间
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    }
  }
}
</script>

<style scoped>
.chat-page {
  min-height: 100vh;
  background: #f5f7fa;
  box-sizing: border-box;
}

/* 导航栏 */
.navbar {
  background: #0ea5a5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 16rpx;
  padding-right: 16rpx;
  padding-bottom: 10rpx;
  color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  box-sizing: border-box;
}

.nav-left, .nav-right {
  width: 80rpx;
}

.icon-back {
  font-size: 48rpx;
  font-weight: bold;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
}

/* 聊天内容区域 */
.chat-content {
  min-height: 100vh;
  padding-left: 24rpx;
  padding-right: 24rpx;
  padding-bottom: 200rpx;
  box-sizing: border-box;
}

/* 消息项 */
.message-item {
  display: flex;
  margin-bottom: 32rpx;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.bot-message {
  justify-content: flex-start;
}

.user-message {
  justify-content: flex-end;
}

/* 头像 */
.avatar {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.bot-avatar {
  background: #0ea5a5;
  margin-right: 16rpx;
}

.bot-avatar image {
  width: 100%;
  height: 100%;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 16rpx;
}

.avatar-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: 600;
}

/* 消息包裹器 */
.message-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 500rpx;
}

.user-message .message-wrapper {
  align-items: flex-end;
}

.bot-message .message-wrapper {
  align-items: flex-start;
}

/* 消息气泡 */
.message-bubble {
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  word-break: break-all;
  white-space: pre-wrap;
}

.bot-bubble {
  background: #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.user-bubble {
  background: linear-gradient(135deg, #0ea5a5 0%, #0c8f8f 100%);
  color: #fff;
}

.message-text {
  font-size: 28rpx;
  line-height: 1.6;
}

.message-time {
  font-size: 20rpx;
  color: #9ca3af;
  margin-top: 8rpx;
}

/* 加载动画 */
.typing {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 24rpx 32rpx;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #0ea5a5;
  animation: typing 1.4s infinite;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.3;
  }
  30% {
    transform: translateY(-12rpx);
    opacity: 1;
  }
}

/* 快捷问题浮动按钮 */
.quick-float-btn {
  position: fixed;
  bottom: 330rpx;
  right: 24rpx;
  width: 88rpx;
  height: 88rpx;
  background: linear-gradient(135deg, #0ea5a5 0%, #0c8f8f 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(14, 165, 165, 0.4);
  z-index: 100;
}

.quick-icon {
  font-size: 40rpx;
}

/* 快捷问题弹窗遮罩 */
.quick-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 快捷问题弹窗 */
.quick-dialog {
  width: 640rpx;
  max-height: 70vh;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(40rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 弹窗标题栏 */
.quick-header {
  padding: 32rpx 32rpx 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #e5e7eb;
  background: linear-gradient(135deg, #0ea5a5 0%, #0c8f8f 100%);
}

.quick-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #fff;
}

.quick-close {
  font-size: 56rpx;
  color: #fff;
  line-height: 1;
  padding: 0 8rpx;
}

/* 快捷问题列表 */
.quick-list {
  max-height: 60vh;
  overflow-y: auto;
  padding: 16rpx;
}

.quick-item {
  display: flex;
  align-items: center;
  padding: 24rpx 20rpx;
  margin-bottom: 12rpx;
  background: #f0faf9;
  border-radius: 16rpx;
  border: 2rpx solid #0ea5a5;
  transition: all 0.3s;
}

.quick-item:active {
  background: #0ea5a5;
  transform: scale(0.98);
}

.quick-item:active .quick-text {
  color: #fff;
}

.quick-icon-small {
  font-size: 32rpx;
  margin-right: 16rpx;
}

.quick-text {
  flex: 1;
  font-size: 28rpx;
  color: #0ea5a5;
  font-weight: 600;
}

/* 输入栏 */
.input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  gap: 16rpx;
  border-top: 1rpx solid #e5e7eb;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 998;
}

.input-text {
  flex: 1;
  background: #f3f4f6;
  height: 72rpx;
  border-radius: 36rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
}

.send-btn {
  width: 120rpx;
  height: 72rpx;
  background: #d1d5db;
  color: #fff;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: 600;
  transition: all 0.3s;
}

.send-btn.active {
  background: linear-gradient(135deg, #0ea5a5 0%, #0c8f8f 100%);
}
</style>

